package com.zhangxun.config;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
public class MessageConfig implements CommandLineRunner {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Value("${token.url}")
    private String tokenUrl;

    @Override
    public void run(String... args) throws Exception {
        getAccessToken();
    }


    public void getAccessToken(){
        String str = HttpUtil.get(tokenUrl);
        JSONObject jsonObject = JSON.parseObject(str);

        String access_token = jsonObject.getString("access_token");
        if(StringUtils.hasText(access_token)){
            stringRedisTemplate.opsForValue().set("access_token", access_token);
        }
    }

    @Scheduled(initialDelay = 1000*60*119,fixedDelay = 1000 * 60*119)
    public void timeToGetToken(){
        getAccessToken();
    }


}
